package com.trsvax.gwthello.client.gwtui.widgets;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.datepicker.client.DatePicker;
import com.trsvax.gwthello.client.Tapestry;
import com.trsvax.gwthello.client.gwtui.services.DatePickerService;
import com.trsvax.gwthello.client.gwtui.services.DatePickerServiceAsync;

public class DatePickerWidget extends Composite {
	private final DatePickerServiceAsync dateService = GWT.create(DatePickerService.class);
	String id;
	Dictionary dictionary;

	public DatePickerWidget(String id, Dictionary dictionary) {
		DatePicker datepicker = new DatePicker();
		((ServiceDefTarget) dateService).setServiceEntryPoint(dictionary.get("completeID"));

		this.id = id;
		this.dictionary = dictionary;

		datepicker.addValueChangeHandler(new ValueChangeHandler<Date>() {
			public void onValueChange(ValueChangeEvent<Date> event) {
				Date date = event.getValue();
				GWT.log("date clicked " + date, null);
				sendDate(date);
			}
		});

		initWidget(datepicker);
	}

	void sendDate(Date value) {
		dateService.date(value, new AsyncCallback<String>() {
			public void onFailure(Throwable caught) {

			}

			public void onSuccess(String result) {
				String zone = dictionary.get("zone");
				if (zone != null)
					Tapestry.loadZone(zone, "/examples/DatePicker:newdate");
				GWT.log("event processed", null);

			}
		});
	}

}
